import { useState, useEffect, useRef } from 'react';
import api from '../utils/api';
import { message } from 'antd';

/**
 * useApi - 简单的请求Hook封装
 * @param {string} url - 请求地址
 * @param {object} options - 请求配置
 *  - method: 请求方法，默认 'get'
 *  - params: get请求参数
 *  - data: post/put请求体数据
 *  - manual: 是否手动触发，默认 false（自动请求）
 *  - config: axios额外配置
 * @returns {object} { data, error, loading, run }
 */
export default function useApi(
    url,
    {
        method = 'get',
        params = {},
        data = {},
        manual = false,
        config = {}
    } = {}
) {
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const [responseData, setResponseData] = useState(null);
    const cancelRef = useRef(null);

    // 发送请求函数
    const run = async (overrideParams = {}, overrideData = {}) => {
        setLoading(true);
        setError(null);

        // 如果上一个请求没结束，先取消
        if (cancelRef.current) {
            cancelRef.current();
        }

        try {
            // axios CancelToken 用法，方便组件卸载时取消请求
            const source = api.CancelToken.source();
            cancelRef.current = source.cancel;

            let res;
            if (method.toLowerCase() === 'get') {
                res = await api.get(url, { params: { ...params, ...overrideParams }, cancelToken: source.token, ...config });
            } else if (method.toLowerCase() === 'post') {
                res = await api.post(url, { ...data, ...overrideData }, { cancelToken: source.token, ...config });
            } else if (method.toLowerCase() === 'put') {
                res = await api.put(url, { ...data, ...overrideData }, { cancelToken: source.token, ...config });
            } else if (method.toLowerCase() === 'delete') {
                res = await api.delete(url, { params: { ...params, ...overrideParams }, cancelToken: source.token, ...config });
            } else {
                throw new Error(`useApi 不支持请求方法: ${method}`);
            }

            setResponseData(res);
            setLoading(false);
            cancelRef.current = null;
            return res;
        } catch (err) {
            setLoading(false);
            setError(err);
            cancelRef.current = null;

            // 错误提示由 api 拦截器处理，这里可以选是否二次提示
            if (!api.isCancel(err)) {
                message.error(err.response?.data?.error || '请求失败');
            }

            throw err; // 抛出错误供外层捕获
        }
    };

    // 自动请求逻辑
    useEffect(() => {
        if (!manual && url) {
            run();
        }

        // 组件卸载时取消请求
        return () => {
            if (cancelRef.current) {
                cancelRef.current();
            }
        };
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [url]);

    return {
        data: responseData,
        loading,
        error,
        run,  // 手动触发请求
    };
}
